package moe.service;

import java.util.logging.Logger;

import moe.config.Configuration;

public class Browser {
	private final static Logger log = Logger.getLogger(Browser.class.getName());

	public static void open() {
		String url = "http://localhost:" + Configuration.getPort();
		try {
			String osName = System.getProperty("os.name", "linux").toLowerCase();
			Runtime rt = Runtime.getRuntime();
			/*
			String browser = Utils.getProperty(SysProperties.H2_BROWSER, null);
			if (browser != null) {
			    if (browser.startsWith("call:")) {
			        browser = browser.substring("call:".length());
			        Utils.callStaticMethod(browser, url);
			    } else if (browser.indexOf("%url") >= 0) {
			        String[] args = StringUtils.arraySplit(browser, ',', false);
			        for (int i = 0; i < args.length; i++) {
			            args[i] = StringUtils.replaceAll(args[i], "%url", url);
			        }
			        rt.exec(args);
			    } else if (osName.indexOf("windows") >= 0) {
			        rt.exec(new String[] { "cmd.exe", "/C",  browser, url });
			    } else {
			        rt.exec(new String[] { browser, url });
			    }
			    return;
			}*/
			/*
			try {
				Class<?> desktopClass = Class.forName("java.awt.Desktop");
				URI uri = new URI(url);
				if (Desktop.isDesktopSupported()) {
					Desktop desktop = Desktop.getDesktop();
					desktop.browse(uri);
					return;
				}
			} catch (Exception e) {
				// ignore
			}*/
			if (osName.indexOf("windows") >= 0) {
				rt.exec(new String[] { "rundll32", "url.dll,FileProtocolHandler", url });
			} else if (osName.indexOf("mac") >= 0 || osName.indexOf("darwin") >= 0) {
				// Mac OS: to open a page with Safari, use "open -a Safari"
				Runtime.getRuntime().exec(new String[] { "open", url });
			} else {
				String[] browsers =
						{ "firefox", "mozilla-firefox", "mozilla", "opera", "chrome", "konqueror",
								"netscape" };
				boolean ok = false;
				for (String b : browsers) {
					try {
						rt.exec(new String[] { b, url });
						ok = true;
						break;
					} catch (Exception e) {
						// ignore and try the next
					}
				}
				if (!ok) {
					// No success in detection.
					//throw new Exception("Browser detection failed and system property "
					//		+ SysProperties.H2_BROWSER + " not set");
					log.warning("Browser detection failed");
				}
			}
		} catch (Exception e) {
			//throw new RuntimeException("Failed to start a browser to open the URL " + url + ": "
			//		+ e.getMessage());
			log.warning("Failed to start a browser to open the URL " + url + ": " + e.getMessage());
		}
		System.gc();
	}
}
